package com.google.code.mergeinformer.model.security;

import com.google.code.mergeinformer.model.DefaultEntity;
import org.hibernate.validator.constraints.NotBlank;

import javax.persistence.*;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Dmitriy Golubev
 */
@Entity
@Table(name = "authority_group")
public class AuthorityGroup extends DefaultEntity implements Serializable {

    @NotBlank
    @Size(max = 32)
    @Column(name = "name", nullable = false)
    private String name;

    @ManyToMany
    @JoinTable(
            name = "app_user2authority_group",
            joinColumns = @JoinColumn(name = "id_authority_group"),
            inverseJoinColumns = @JoinColumn(name = "id_app_user")
    )
    private Set<User> users = new HashSet<>();

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "authority_group2authority",
            joinColumns = @JoinColumn(name = "id_authority_group"),
            inverseJoinColumns = @JoinColumn(name = "id_authority")
    )
    private Set<Authority> authorities = new HashSet<>();

    public String getName() {
        return name;
    }

    public Set<User> getUsers() {
        return users;
    }

    public Set<Authority> getAuthorities() {
        return authorities;
    }

    public void setAuthorities(Set<Authority> authorities) {
        this.authorities = authorities;
    }

    public void addAuthority(Authority authority) {
        if (authority != null && !authorities.contains(authority)) {
            authorities.add(authority);
            authority.addAuthorityGroup(this);
        }
    }

    void addUser(User user) {
        if (user != null && !users.contains(user)) {
            users.add(user);
        }
    }
}
